#include "func_ls.h"

void func_ls(int peerfd,char *filename)
{
    // ./ls dir 
    // 打开目录
    if(filename[0] == '\0') filename[0] = '.';
    DIR *pdir = opendir(filename);

    ERROR_CHECK(pdir,NULL,"opendir");

    // 读目录项
    struct dirent* pdirent;
    errno = 0;

    char sendresult[1000]={0};
    while((pdirent = readdir(pdir)) != NULL) {
        // 忽略隐藏文件和隐藏文件夹
        char *name = pdirent->d_name;
        if (name[0] == '.') {
            continue;
        }
        //将输出结果存储在sendresult数组中
        sprintf(sendresult,"%s %s",sendresult,name);
    }
    //printf("strlength:%ld \n content:%s\n", strlen(sendresult),sendresult);
    //printf("\n");
    //printf("the result of func_ls is stored.\n");
    // 错误处理
    if (errno != 0) {
        perror("readdir");
        exit(1);
    }
    // 关闭目录流
    closedir(pdir);
    write(peerfd,sendresult,strlen(sendresult));
    //printf("the result of sending is finished.\n");
}

